<template>
    <userDialog
        v-model="visible"
        :dialogTitle="`${userGroupDialogType}用户`"
        width="880px"
        @open="init"
        @handleCloseDialog="handleCloseDialog(false)"
    >
        <template v-slot:userDiagContent>
            <dialogFormContent title="基本信息">
                <template v-slot:form_info="{ isShowInfoFold }">
                    <div v-show="isShowInfoFold">
                        <el-form
                            :rules="addUserGroupFromRules"
                            :model="form"
                            class="user_form_content"
                            ref="queryFormRef"
                        >
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item
                                        label="用户组名称："
                                        prop="name"
                                    >
                                        <el-input
                                            v-model="form.name"
                                            placeholder="请输入用户组名称"
                                        />
                                    </el-form-item>
                                </el-col>

                                <el-col :span="12">
                                    <el-form-item
                                        label="用户组描述："
                                        prop="describe"
                                    >
                                        <el-input
                                            type="textarea"
                                            autosize
                                            v-model="form.describe"
                                            placeholder="请输入用户组描述"
                                        />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </div>
                </template>
            </dialogFormContent>
            <dialogFormContent title="权限信息">
                <template v-slot:form_info="{ isShowInfoFold }">
                    <div v-show="isShowInfoFold">
                        <rolePerssion
                            ref="rolePerssionRef"
                            :checkList="roleList"
                            :isNeedDefaultUser="false"
                        ></rolePerssion>
                    </div>

                    <!-- <ShowMore
                        show-text-tips="添加其他权限(自定义)"
                        close-text-tips="隐藏其他权限(自定义)"
                        background="#f6f9ff"
                    >
                        <template v-slot:form_info="{ visible }">
                            <div v-show="visible">
                                <appRolePerssion
                                    ref="appRolePerssionRef"
                                    class="mt-20px"
                                    :checkList="appList"
                                ></appRolePerssion>
                                <menusManagerSlelet
                                    ref="menusManagerSleletRef"
                                    v-model:menuList="menuList"
                                ></menusManagerSlelet>
                            </div>
                        </template>
                    </ShowMore> -->

                    <appRolePerssion
                        ref="appRolePerssionRef"
                        class="mt-20px"
                        :checkList="appList"
                    ></appRolePerssion>
                    <menusManagerSlelet
                        ref="menusManagerSleletRef"
                        v-model:menuList="menuList"
                    ></menusManagerSlelet>
                </template>
            </dialogFormContent>
            <div class="btnStyle mt-20px">
                <el-button type="primary" @click="upData()"> 提交 </el-button>
                <el-button type="info" @click="handleCloseDialog()">
                    重置
                </el-button>
            </div>
        </template>
    </userDialog>
</template>

<script setup lang="ts">
import UserAPI from "@/api/system/user";
import MenuAPI from "@/api/system/menu";
import UserGroupAPI from "@/api/system/userGroup";
import { addUserGroupFromRules } from "@/views/system/userGroupManager/index";
const emit = defineEmits(["reFresh"]);
const visible = defineModel("modelValue", {
    type: Boolean,
    required: true,
    default: false,
});

const props = defineProps({
    userGroupDialogType: {
        required: true,
        default: () => "添加" as any,
    },
    userGroupId: {
        required: true,
        default: () => "",
    },
});
const queryFormRef = ref();
const rolePerssionRef = ref();
const appRolePerssionRef = ref();
const menusManagerSleletRef = ref();
const form = ref({
    name: "",
    describe: "",
});

// 下拉列表类型
interface elselect {
    label: string;
    value: string;
}
const roleList = ref([] as elselect[]);
const appList = ref([] as elselect[]);
const menuList = ref([] as any[]);

async function getAllCommonUserInfo() {
    return Promise.all([
        // 获取角色列表
        UserAPI.getRoleList().then((data) => {
            roleList.value = data.map((item: any) => {
                return {
                    label: item.type_name,
                    value: item.id,
                };
            });
        }),
        // 获取app列表
        UserAPI.getAppList().then((data) => {
            appList.value = data.map((item: any) => {
                return {
                    label: item.name,
                    value: item.id,
                };
            });
        }),
        // 获取菜单列表
        MenuAPI.getOptions().then((data) => {
            deepEdit(data);
            menuList.value = data;
        }),
    ]).catch((error) => {
        throw error;
    });
}

//
function deepEdit(data: any, parent = null) {
    data.forEach((item: any) => {
        item.chooseStatus = "noneSelect";
        item.choosed = false;
        item.actived = false;
        item.parent = parent;
        if (item.children) {
            deepEdit(item.children, item);
        }
    });
}

// 初始化表单
async function init() {
    await getAllCommonUserInfo();

    if (props.userGroupDialogType === "编辑" && props.userGroupId) {
        await getUserDetail();
    }
}

// 获取编辑用户组人员信息
async function getUserDetail() {
    let id = props.userGroupId;
    await UserGroupAPI.getUserGroupInfo(id)
        .then((data: any) => {
            putUserDetail(data);
        })
        .catch((err: any) => {
            console.log(err);
        });
}

// 回写详情信息
async function putUserDetail(data: any) {
    //基本信息
    form.value.name = data.detail.name;
    form.value.describe = data.detail.describe;

    //角色权限
    let arr: any = [];

    console.log("000");
    roleList.value.forEach((item: any) => {
        if (data.user_type_ids.includes(Number(item.value))) {
            arr.push(String(item.value));
        }
    });
    rolePerssionRef.value.formObj.roleCheckoutList = arr;

    //小程序权限
    appRolePerssionRef.value.appCheckoutList =
        data.menus.front_operation_ids.map((item: any) => {
            return (item = Number(item));
        });
    setChooseData(menuList.value, data.menus.menu_ids);
}

// 选取
const setChooseData = (data: any, resData: any) => {
    data.forEach((ele: any) => {
        if (resData.includes(String(ele.value))) {
            menusManagerSleletRef.value.menusSelect.menuItemChoose(ele, true);
        }

        if (ele.children) {
            setChooseData(ele.children, resData);
        }
    });
};

// 提交
async function upData() {
    //表单校验
    const queryFormIsValid = await queryFormRef.value.validate(
        (isValid: boolean) => {
            return isValid;
        }
    );
    //角色校验
    const rolePerssionValid = await rolePerssionRef.value.roleValidation();
    if (!queryFormIsValid || !rolePerssionValid) {
        return;
    }

    // 表单参数
    let formParams = {
        ...form.value,
    };
    // 角色参数
    let roleParams = {
        alltype: rolePerssionRef.value.formObj.roleCheckoutList,
    };
    let appParams = {
        front_operation_ids: appRolePerssionRef?.value?.appCheckoutList || [],
    };
    let menusManagerParams = {
        menu_ids:
            menusManagerSleletRef.value.choosedList?.map((item: any) => {
                return item.value;
            }) || [],
    };

    let api = UserGroupAPI.addUserGroup;
    let params: any = {
        ...formParams,
        ...roleParams,
        ...appParams,
        ...menusManagerParams,
    };
    if (props.userGroupDialogType === "编辑" && props.userGroupId) {
        api = UserGroupAPI.editUserGroupInfo;
        params.id = props.userGroupId;
    }

    await api(params)
        .then((data: any) => {
            visible.value = false;
            emit("reFresh");
            ElMessage.success(`${props.userGroupDialogType}成功`);
        })
        .catch((err: any) => {
            console.log(err);
        });
}

function handleCloseDialog(visibleValue = true) {
    if (!visibleValue) {
        visible.value = visibleValue;
    }

    queryFormRef.value.resetFields();
    queryFormRef.value.clearValidate();

    rolePerssionRef.value.roleCheckRef.resetFields();
    rolePerssionRef.value.roleCheckRef.clearValidate();

    appRolePerssionRef.value.appCheckoutList = [];

    menusManagerSleletRef.value.allReset();
}
</script>

<style lang="scss" scoped>
.btnStyle {
    padding: 0 255px;
    @include flexLayout;
    justify-content: space-between;
    .el-button {
        font-size: 16px;
        padding: 20px 40px;
    }
}
.user_form_content {
    :deep(.el-form-item) {
        display: flex;

        label {
            width: 110px;
        }
        .el-input,
        .el-cascader,
        .el-select {
            height: 32px;
            width: 100%;
            .el-select__wrapper {
                height: 32px;
                line-height: 32px;
            }
        }
    }
}
</style>
